﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Input;
using System.Xml;
using System.Xml.Serialization;
using UpdateClient.ICommandNotify;
using UpdateClient.Model;

namespace UpdateClient
{
    public class VersionWindowViewModel
    {
        public VersionWindowViewModel(List<FileModel> VersionList,string path)
        {
            DataModel = new VersionWindowModel();
            DataModel.VersionList = VersionList;
            Detailcommand = new Command(Detailcommand_);
            returnVersioncommand=new Command(returnVersioncommand_);
            TestVersioncommand = new Command(TestVersioncommand_);
            DataModel.path = path;
        }

        private async void TestVersioncommand_(object obj)
        {
            // 创建 FolderBrowserDialog 实例
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            // 显示对话框
            DialogResult result = folderBrowserDialog.ShowDialog();
            if (result == DialogResult.OK)
            {
                var BaseDirectorypath = System.AppDomain.CurrentDomain.BaseDirectory;
                //初始化文件保存路径
                var SourcePubliFile = Path.Combine(BaseDirectorypath, $"publishFileinfo\\{obj.ToString().Replace("版本号:","")}");
                await ExtractZip(SourcePubliFile, folderBrowserDialog.SelectedPath, Updateprogress("正在解析文件"), obj as string);
                DataModel.ProgressBarDescribe = "文件已保存完成";
            }

          
        }
        /// <summary>
        /// 更新进度条
        /// </summary>
        private IProgress<int> Updateprogress(string Content)
        {
            DataModel.ProgressBarDescribe = Content;
            var progress = new Progress<int>(percent =>
            {
                // 这里更新UI或者其他进度条
                DataModel.ProgressBarValue = percent;
            });
            return progress;
        }
        /// <summary>
        /// 解压
        /// </summary>
        /// <param name="zipFilePath"></param>
        /// <param name="destinationFolder"></param>
        private async Task ExtractZip(string zipFilePath, string destinationFolder, IProgress<int> progress,string d)
        {
            // 检查 ZIP 文件是否存在
            if (!Directory.Exists(zipFilePath))
            {
                return;
            }
            await Task.Run(() =>
            {
                // 如果目标文件夹不存在，则创建它
                if (!Directory.Exists(destinationFolder))
                {
                    Directory.CreateDirectory(destinationFolder);
                }
                try
                {
                    string[] files = Directory.GetFiles(zipFilePath, "*.zip", SearchOption.AllDirectories);

                    int totalFiles = files.Length;
                    int filesExtracted = 0;
                    UpdateInfo person = xmlUpdateInfo(zipFilePath);
                    foreach (var item in files)
                    {
                        string name = Path.GetFileName(item);
                        UpdateInfoDtl updateInfo = person.Dtls.FirstOrDefault(o => o.PackageName == name);
                        if (updateInfo != null && updateInfo.FilePath.Contains("\\"))
                        {
                            //if (!Directory.Exists($"{destinationFolder}\\{Path.GetDirectoryName(updateInfo.FilePath)}"))
                            //{
                            //    Directory.CreateDirectory($"{destinationFolder}\\{Path.GetDirectoryName(updateInfo.FilePath)}");
                            //}
                            ZipFile.ExtractToDirectory(item, $"{destinationFolder}\\{Path.GetDirectoryName(updateInfo.FilePath)}");
                        }
                        else
                        {
                            ZipFile.ExtractToDirectory(item, destinationFolder);


                        }
                        // 更新进度
                        filesExtracted++;
                        int progressPercent = (int)((float)filesExtracted / totalFiles * 100);
                        progress?.Report(progressPercent);  // 更新进度
                    }
                }
                catch (Exception ex)
                {
                  
                }
            });
        }
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <returns></returns>
        private UpdateInfo xmlUpdateInfo(string lastfilepath)
        {
            // 先读取 XML 文件内容
            string xmlContent = File.ReadAllText(lastfilepath + "\\update.xml");

            // 创建 XmlSerializer 对象
            XmlSerializer serializer = new XmlSerializer(typeof(UpdateInfo));

            UpdateInfo updateInfoList;
            using (StringReader reader = new StringReader(xmlContent))
            {
                // 进行反序列化
                updateInfoList = (UpdateInfo)serializer.Deserialize(reader);
            }
            return updateInfoList;
        }
        private void returnVersioncommand_(object obj)
        {
          System.Windows.Forms. MessageBox.Show("此功能还在开发中");
        }

       public ICommand Detailcommand {  get; set; }
       public ICommand returnVersioncommand {  get; set; }
       public ICommand TestVersioncommand {  get; set; }
       public VersionWindowModel DataModel { get; set; }

        public void Detailcommand_(object s)
        {
          var files=  Directory.GetFiles($"{DataModel.path}\\{s.ToString().Split(':')[1]}", "*.zip");
            DataModel.DetailsList = new List<FileModel>();
            FileInfo fileInfo;
            foreach (var item in files)
            {
                fileInfo = new FileInfo(item);
                DataModel.DetailsList.Add(new FileModel()
                {
                    Name = fileInfo.Name,
                    modificationDate = fileInfo.LastWriteTimeUtc.ToString("yyyy/MM/dd HH:mm:ss"),
                    Size = fileInfo.Length.ToString(),
                    Type = fileInfo.Extension
                });
            }
            Details details = new Details();
            details.DataContext = DataModel;
            details.ShowDialog();
        }
    }
}
